<template>
  <div class="form-box">
    <el-form :model="form" :inline="true" :disabled="isDisabled">
      <el-form-item label="学期:">
        <el-select
          class="select"
          v-model="form.semester"
          placeholder="请选择学期"
          @change="semesterHandle"
        >
          <el-option
            v-for="option in semesterOption"
            :key="option.id"
            :label="option.name"
            :value="option.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学科:">
        <el-select
          class="select"
          v-model="form.discipline"
          placeholder="请选择学科"
          @change="disciplineHandle"
        >
          <el-option
            v-for="option in disciplineOption"
            :key="option.subjectId"
            :label="option.subjectName"
            :value="option.subjectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年级:">
        <el-select
          class="select"
          v-model="form.gradeCode"
          placeholder="请选择年级"
          @change="gradeCodeHandle"
        >
          <el-option
            v-for="item in gradeList"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级类型:">
        <el-select
          class="select"
          v-model="form.classType"
          placeholder="请选择班级类型"
          @change="classTypeHandle"
        >
          <el-option
            v-for="item in classTypeOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级:">
        <el-select
          class="select"
          v-model="form.classId"
          placeholder="请选择班级"
          @change="classIdHandle"
        >
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
export type Form = {
  semester: string // 学期
  discipline: string // 学科
  disciplineName: string // 学科名称

  gradeCode: string // 年级
  gradeId: string // 年级 Id
  gradeName: string // 年级名称

  classType: string // 班级类型
  classId: string // 班级Id
}
const form = ref<Form>({
  semester: '',
  discipline: '',
  disciplineName: '',
  gradeId: '',
  gradeCode: '',
  gradeName: '',
  classType: '1',
  classId: ''
})

type GradeList = {
  id: string
  code: string
  name: string
  sortOrder: number
}
type ClassList = {
  id: string
  name: string
}
interface SemesterOption {
  id: string
  name: string
  endDate: string
  startDate: string
  endTimestamp: number
  startTimestamp: number
}

interface DisciplineOption {
  subjectId: string
  subjectName: string
}
interface ClassTypeOption {
  id: string
  label: string
}
// 添加一个标记来跟踪初始化状态
const isInitialized = ref(false)

// 年级
const gradeList = ref<GradeList[]>([])

// 班级
const classList: Ref<ClassList[]> = ref([])

// 学期
const semesterOption = ref<SemesterOption[]>([])

// 科学
const disciplineOption = ref<DisciplineOption[]>([])

// 班级类型
const classTypeOption = ref<ClassTypeOption[]>([
  {
    id: '2',
    label: '教学班'
  },
  {
    id: '1',
    label: '行政班'
  }
])

const Emit = defineEmits<{
  (e: 'formChangeHandle', data: Form): void
}>()

// 学期事件
const semesterHandle = () => {
  Emit('formChangeHandle', form.value)
  console.log(form.value)
}

// 布置课程锁死筛选框
const props = defineProps<{
  isArrange: boolean
}>()
const isDisabled = ref<boolean>(props.isArrange)
watch(
  () => props.isArrange,
  (newVal) => {
    isDisabled.value = newVal
  }
)

// 学科事件
const disciplineHandle = (val: string) => {
  const currentData = disciplineOption.value.find(
    (item: DisciplineOption) => item.subjectId === val
  )
  form.value.discipline = currentData?.subjectId || ''
  form.value.disciplineName = currentData?.subjectName || ''
  Emit('formChangeHandle', form.value)
}
// 年级事件
const gradeCodeHandle = (val: string) => {
  const currentData = gradeList.value.find(
    (item: GradeList) => item.code === val
  )
  form.value.gradeCode = currentData?.code || ''
  form.value.gradeId = currentData?.id || ''
  form.value.gradeName = currentData?.name || ''
  form.value.classId = ''
  getClassByTeacherId()
  // Emit('formChangeHandle', form.value)
}
// 班级类型
const classTypeHandle = () => {
  form.value.classId = ''
  getClassByTeacherId()
}
// 班级
const classIdHandle = () => {
  Emit('formChangeHandle', form.value)
}

// 学期
const getQuerySemesterListH5Api = () => {
  semesterOption.value = [
    {
      id: '1984139593338851328',
      name: '2025下学期',
      startDate: '2025-09-01',
      endDate: '2026-02-26',
      endTimestamp: 0,
      startTimestamp: 0
    },
    {
      id: '1984142114845364224',
      name: '2025上学期',
      startDate: '2025-10-01',
      endDate: '2025-10-31',
      endTimestamp: 0,
      startTimestamp: 0
    }
  ]

  /**
   * 此处规则：
   * （1）默认显示当前时间所在的学期，取 startDate< 当前时间 < endDate  这条数据为默认显示数据；
   * （2）如果当前时间不在（1）规则内，就取 endDate 最大的时间，这条数据
   * 以下代码实现上面的逻辑
   */
  // 开始时间转换时间戳
  semesterOption.value.forEach((item: SemesterOption) => {
    // 将日期字符串转换为时间戳
    const startTimestamp = new Date(item.startDate).getTime()
    const endTimestamp = new Date(item.endDate).getTime()
    // 将时间戳存储回对象
    item.startTimestamp = startTimestamp
    item.endTimestamp = endTimestamp
  })

  // 找出当前时间在范围内的数据
  const currentTimestamp = Date.now()
  let currentSemester = semesterOption.value.find((item: SemesterOption) => {
    return (
      currentTimestamp >= item.startTimestamp &&
      currentTimestamp <= item.endTimestamp
    )
  })
  // 如果没找到，就取结束时间最大的数据
  if (!currentSemester && semesterOption.value.length) {
    currentSemester = semesterOption.value.reduce((prev, current) => {
      return prev.endTimestamp > current.endTimestamp ? prev : current
    })
  }
  // 将上面规则查找到的数据 复制给 form.value.semester 显示默认展示的数据
  form.value.semester = currentSemester?.id || ''
  // 初始化完成后触发 emit
  checkAndEmitFormData()
}

// 学科
const getDisciplineApi = () => {
  disciplineOption.value = [
    {
      subjectId: '1851528914003673090',
      subjectName: '语文'
    }
  ]
  // 判断当前 是否有数据
  if (disciplineOption.value === null || disciplineOption.value.length === 0)
    return
  // 如果有数据 就获取第一个数据 默认显示 复制给 form.value.discipline
  form.value.discipline = disciplineOption.value[0].subjectId
  form.value.disciplineName = disciplineOption.value[0].subjectName
  // 调用 年级 Api接口
  selectorLabelApi()
}

// 年级Api
const selectorLabelApi = () => {
  // 年级信息
  gradeList.value = [
    {
      id: '1852160915593306113',
      name: '七年级',
      code: 'D8Av14',
      sortOrder: 0
    }
  ]
  // 判断当前 是否有数据
  if (!gradeList.value || gradeList.value.length === 0) return
  // 如果有数据 就获取第一个数据 默认显示 复制给 form.value.gradeCode
  form.value.gradeCode = gradeList.value[0].code
  form.value.gradeId = gradeList.value[0].id
  form.value.gradeName = gradeList.value[0].name
  // 调用班级 Api 接口
  getClassByTeacherId()
}

// 班级
const getClassByTeacherId = () => {
  classList.value = [
    {
      id: '1984138444250550273',
      name: '二班(政)'
    }
  ]
  if (classList.value && classList.value.length > 0) {
    form.value.classId = classList.value[0].id
  }
  // 班级数据加载完成后，标记初始化完成并触发 emit
  isInitialized.value = true
  Emit('formChangeHandle', form.value)
}

// 检查并触发表单数据 emit
const checkAndEmitFormData = () => {
  // 确保所有必要字段都有值后再触发
  if (form.value.semester && form.value.discipline && form.value.gradeCode) {
    Emit('formChangeHandle', form.value)
  }
}

onMounted(() => {
  getQuerySemesterListH5Api()
  getDisciplineApi()
})

defineExpose({
  searchFormData: () => form.value
})
</script>

<style lang="scss" scoped>
.form-box {
  padding-left: 20px;
  .select {
    width: 160px;
  }
}

:deep(.el-form--inline) {
  .el-form-item {
    margin-right: 20px;
  }
}
</style>
